package net.mihome.app.ui;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;

import net.mihome.app.AppContext;
import net.mihome.app.AppException;
import net.mihome.app.R;
import net.mihome.app.bean.Shop;
import net.mihome.app.bean.URLs;
import net.mihome.app.bean.net.ResponsePojo;
import net.mihome.app.common.FileUtils;
import net.mihome.app.common.ImageUtils;
import net.mihome.app.common.StringUtils;
import net.mihome.app.common.UIHelper;
import net.mihome.app.utils.MiAsyncHttpResponseHandler;
import net.mihome.app.utils.RequestParamsFactory;
import net.mihome.app.widget.LoadingDialog;

import org.apache.http.Header;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 用户资料
 * 
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-3-21
 */
public class ShopInfo extends BaseActivity {

	private ImageView face;
	private TextView name;
	private TextView contrac;
	private TextView desc;
	private LoadingDialog loading;
	private Shop shop;
	private Handler mHandler;
	private final static int CROP = 200;
	private final static String FILE_SAVEPATH = Environment
			.getExternalStorageDirectory().getAbsolutePath()
			+ "/OSChina/Portrait/";
	private Uri origUri;
	private Uri cropUri;
	private File protraitFile;
	private Bitmap protraitBitmap;
	private String protraitPath;
    private TextView titleShop;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shop_info);

		// 初始化视图控件
		this.initView();
		// 初始化视图数据
		this.initData();
	}

	private void initView() {

		face = (ImageView) findViewById(R.id.shop_info_userface);
		name = (TextView) findViewById(R.id.shop_info_username);
		contrac = (TextView) findViewById(R.id.shop_info_contract);
		desc = (TextView) findViewById(R.id.shop_info_desc);
        titleShop= (TextView) findViewById(R.id.shop_detail_head_title);
	}

	private void initData() {
		mHandler = new Handler() {
			public void handleMessage(Message msg) {
				if (loading != null)
					loading.dismiss();
				if (msg.what == 1 && msg.obj != null) {
					shop = (Shop) msg.obj;

					// 加载用户头像
                    if(shop.getShopType()!=null){
                        UIHelper.showUserFace(face, shop.getShopType().getAvatar());
                    }

					// 其他资料
					name.setText(shop.getName());
                    titleShop.setText(shop.getName());
					contrac.setText(shop.getContract() + "");
                    ((TextView)findViewById(R.id.shop_call_sum)).setText(shop.getCallSum() + "");
                    ((TextView)findViewById(R.id.shop_info_desc)).setText(shop.getDesc()+"");
                    ((TextView)findViewById(R.id.shop_info_contract)).setText(shop.getContract() + "");
                    View supportView=findViewById(R.id.shop_support);
                    supportView.setTag(shop);
                    View trampleView=findViewById(R.id.shop_trample);
                    trampleView.setTag(shop);
                    addSupportLinster(supportView);
                    addTrampLinster(trampleView);
				} else if (msg.obj != null) {
					((AppException) msg.obj).makeToast(ShopInfo.this);
				}
			}
		};
		this.loadUserInfoThread(getIntent().getExtras().getInt("shop_id"));
	}

	private void loadUserInfoThread(final int shop_id) {
		loading = new LoadingDialog(this);
		loading.show();

		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					Shop shop = ((AppContext) getApplication())
							.getShopDetail(shop_id);
					msg.what = 1;
					msg.obj = shop;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				mHandler.sendMessage(msg);
			}
		}.start();
	}


	private View.OnClickListener refreshClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			loadUserInfoThread(getIntent().getExtras().getInt("shop_id"));
		}
	};

	private View.OnClickListener favoritesClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			UIHelper.showUserFavorite(v.getContext());
		}
	};

	private View.OnClickListener fansClickListener = new View.OnClickListener() {
		public void onClick(View v) {
		}
	};

	private View.OnClickListener followersClickListener = new View.OnClickListener() {
		public void onClick(View v) {
		}
	};

	// 裁剪头像的绝对路径
	private Uri getUploadTempFile(Uri uri) {
		String storageState = Environment.getExternalStorageState();
		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			File savedir = new File(FILE_SAVEPATH);
			if (!savedir.exists()) {
				savedir.mkdirs();
			}
		} else {
			UIHelper.ToastMessage(ShopInfo.this, "无法保存上传的头像，请检查SD卡是否挂载");
			return null;
		}
		String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
				.format(new Date());
		String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(uri);

		// 如果是标准Uri
		if (StringUtils.isEmpty(thePath)) {
			thePath = ImageUtils.getAbsoluteImagePath(ShopInfo.this, uri);
		}
		String ext = FileUtils.getFileFormat(thePath);
		ext = StringUtils.isEmpty(ext) ? "jpg" : ext;
		// 照片命名
		String cropFileName = "osc_crop_" + timeStamp + "." + ext;
		// 裁剪头像的绝对路径
		protraitPath = FILE_SAVEPATH + cropFileName;
		protraitFile = new File(protraitPath);

		cropUri = Uri.fromFile(protraitFile);
		return this.cropUri;
	}

	// 拍照保存的绝对路径
	private Uri getCameraTempFile() {
		String storageState = Environment.getExternalStorageState();
		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			File savedir = new File(FILE_SAVEPATH);
			if (!savedir.exists()) {
				savedir.mkdirs();
			}
		} else {
			UIHelper.ToastMessage(ShopInfo.this, "无法保存上传的头像，请检查SD卡是否挂载");
			return null;
		}
		String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
				.format(new Date());
		// 照片命名
		String cropFileName = "osc_camera_" + timeStamp + ".jpg";
		// 裁剪头像的绝对路径
		protraitPath = FILE_SAVEPATH + cropFileName;
		protraitFile = new File(protraitPath);
		cropUri = Uri.fromFile(protraitFile);
		this.origUri = this.cropUri;
		return this.cropUri;
	}




	public void addLinserToCall(View view){
		view.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				TextView textView=(TextView) arg0.findViewById(R.id.shop_info_contract);
				String phoneNums=textView.getText().toString();
				// TODO Auto-generated method stub
				if(phoneNums!=null){
					String[] items=phoneNums.split("、|,");
					boolean[] isCheck={true,false};
					UIHelper.simpleDialog(ShopInfo.this,items);
				}
			}
		});
	}
	public void addLinserToMap(View view){
		view.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
//				TextView lonTextView=(TextView) ShopInfo.this.findViewById(R.id.shop_info_lon);
//				TextView latTextView=(TextView) ShopInfo.this.findViewById(R.id.shop_info_lat);
				if(isGpsOpen()){
					String lonString=shop.getLon().toString();
					String latString=shop.getLat().toString();

					if(lonString==null||latString==null||lonString.trim().equals("")||latString.trim().equals("")){
						Toast.makeText(ShopInfo.this,"此商店暂无定位信息",Toast.LENGTH_SHORT).show();
						return ;
					}
                    Toast.makeText(ShopInfo.this,"此商店暂无定位信息",Toast.LENGTH_SHORT).show();
//					Intent intent=new Intent(ShopInfo.this,RoutePlanDemo.class);
//					intent.putExtra("x",Double.parseDouble(lonString));
//					intent.putExtra("y",Double.parseDouble(latString));
//					intent.putExtra("shop",shop);
//					startActivity(intent);
				}else{
					//如果gps未开启
					new AlertDialog.Builder(ShopInfo.this).setTitle("GPS定位未开启").setMessage("是否去设置GPS定位?").setPositiveButton("确定", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							 Intent intent = new Intent();
						        intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
						        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						        try 
						        {
						            ShopInfo.this.startActivity(intent);
						        } catch(ActivityNotFoundException ex) 
						        {
						            intent.setAction(Settings.ACTION_SETTINGS);
						            try {
						            	ShopInfo.this.startActivity(intent);
						            } catch (Exception e) {
						            }
						        }							
						}
					}).setNegativeButton("放弃",new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					}).show();     
				}
			}
		});
	}
	public void addLinserShopMenus(View view){
			view.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent=new Intent(ShopInfo.this,MihomeShopMenusActivity.class);
				String lonString=shop.getLon().toString();
				String latString=shop.getLat().toString();

				if(lonString==null||latString==null||lonString.trim().equals("")||latString.trim().equals("")){
					Toast.makeText(ShopInfo.this,"此商店暂无定位信息",Toast.LENGTH_SHORT).show();
					return ;
				}
				intent.putExtra("x",Double.parseDouble(lonString));
				intent.putExtra("y",Double.parseDouble(latString));
				intent.putExtra("shop", shop);
				startActivity(intent);
			}
		});
	}
	public void addLinserShowJoinTime(View view){
		view.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
                Toast.makeText(ShopInfo.this,"此商店暂无定位信息",Toast.LENGTH_SHORT).show();
			}
		});
	}
	 public boolean  isGpsOpen() {
         LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
         boolean GPS_status = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
         if (!GPS_status) {
             return false;
         } else {
             return true;
         }
     }

    public void addSupportLinster(View view){
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Shop shop= (Shop) view.getTag();
                RequestParams requestParams= RequestParamsFactory.newInstance(AppContext.getInstance());
                requestParams.add("shop_id", shop.getId() + "");
                AppContext.ASYNC_HTTP_CLIENT.get(ShopInfo.this, URLs.MIHOME_GET_SHOP_SUPPORT,requestParams,new MiAsyncHttpResponseHandler<Map>() {
                    @Override
                    public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                        Toast.makeText(ShopInfo.this,"点赞成功",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(int arg0, Header[] arg1, Throwable arg3) {

                    }
                });
            }
        });
    }
    public void addTrampLinster(View view) {
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Shop shop = (Shop) view.getTag();
                RequestParams requestParams = RequestParamsFactory.newInstance(AppContext.getInstance());
                requestParams.add("shop_id", shop.getId() + "");
                AppContext.ASYNC_HTTP_CLIENT.get(ShopInfo.this, URLs.MIHOME_GET_SHOP_TRAMPLE, requestParams, new MiAsyncHttpResponseHandler<Map>() {
                    @Override
                    public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                        Toast.makeText(ShopInfo.this,"操作成功",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(int arg0, Header[] arg1, Throwable arg3) {

                    }
                });
            }
        });
    }
    public void btnEvent(View view){
        if(shop==null){
            Toast.makeText(this,"尚未获取到商铺信息，请稍后..",Toast.LENGTH_SHORT).show();
            return ;
        }
        String contact=shop.getContract();
        if(contact==null){
            Toast.makeText(this,"该商铺暂无联系方式.",Toast.LENGTH_SHORT).show();
            return ;
        }
        callCount(shop);
        String[] items=contact.split(",|，|、");
        UIHelper.simpleDialog(this,items);
    }
    /**
     * 拨打电话的计数
     * */
    public void callCount(Shop shop1){
        RequestParams requestParams=RequestParamsFactory.newInstance(AppContext.getInstance());
        requestParams.put("shop_id",shop1.getId());
        AppContext.ASYNC_HTTP_CLIENT.get(this,URLs.MIHOME_GET_SHOP_CALL_COUNT,requestParams,new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                Toast.makeText(ShopInfo.this,"计数成功",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                Toast.makeText(ShopInfo.this,"计数失败"+arg3.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }
 }
